package com.onemore.task;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import org.voovan.tools.log.Logger;

import com.onemore.task.location.LocTaskSpjhd;
import com.onemore.task.location.LocTaskSpthd;
import com.onemore.task.model.ModelB2CErpWms;
import com.onemore.task.model.ModelB2CWMS;
import com.onemore.task.model.ModelMtab;
import com.onemore.task.model.ModelOneErp2Wms;
import com.onemore.task.model.ModelOneWms;
import com.onemore.task.model.ModelOneWms2Erp;
import com.onemore.task.model.ModelOneWmsTzd;
import com.onemore.task.model.ModelSpjhd;
import com.onemore.task.model.ModelSpthd;

/**
 * ONEMORE 循环定时查询数据库服务  默认编码格式UTF-8
 * @author zzj
 *
 * Voovan Framework.
 * WebSite: https://github.com/helyho/Voovan
 * Licence: Apache v2 License
 */
public class OneServe{
	private List<Map<String, Object>> listMtab = null; 
	private String DJBH;
	private String actType;
	private String tabName;
	private String stamp;
	private int delete_error = 0;
	private String delete_err_str="";
    private int delaySecond = 10;
    private int delayMinute = 0;
    private int retainDay = 0;
		

	/**
	 * 读取日志配置文件信息
	 * @return 日志配置文件对象
	 */
	
	public void serve_auto_clear()
	{
		Calendar calendar = Calendar.getInstance();  
        calendar.set(Calendar.HOUR_OF_DAY,23); // 控制时  
        calendar.set(Calendar.MINUTE, 20);       // 控制分  
        calendar.set(Calendar.SECOND, 0);       // 控制秒  
        Date time = calendar.getTime();         // 得出执行任务的时间,此处为今天的2：00：00  
        Timer timer = new Timer();  
        timer.scheduleAtFixedRate(new TimerTask() {  
            public void run() {  
            	try {
					TimeUnit.DAYS.sleep(1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Logger.info("清理历史"+retainDay+"天前的历史log");
				if(retainDay > 0) {
    				AutoClean autoClean = new AutoClean();
    				autoClean.run(retainDay);
				}
            }  
        }, time, 1000 * 60 * 60 * 24);// 这里设定将延时每天固定执行  
		/*new Thread() {
			@Override
	        public void run() {
				while(true) {
    				try {
						TimeUnit.DAYS.sleep(1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    				Logger.info("retainDay:"+retainDay);
    				if(retainDay > 0) {
	    				AutoClean autoClean = new AutoClean();
	    				autoClean.run(retainDay);
    				}
				}
			}
		}.start();*/
	}
	
	public void serve_auto_import()
	{
		if(ModelOneWms.isNotExist()) {
			try {
        		Logger.info("执行从WMS导出数据到ERP");
        		ModelOneWms.createTable();
        		ModelOneWms.importWmsTable();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Logger.error(e);
			}
		}
		if(ModelOneWmsTzd.isNotExist()) {
			try {
        		Logger.info("执行从WMS导出通知单数据到ERP");
        		ModelOneWmsTzd.createTable();
        		ModelOneWmsTzd.importWmsTableTZD();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Logger.error(e);
			}
		}

		if(ModelB2CWMS.isNotExist()) {
			try {
        		Logger.info("执行从WMS导出B2C数据到ERP");
        		ModelB2CWMS.createTable();
        		ModelB2CWMS.importWmsTable();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Logger.error(e);
			}
		}
///////////////////////////以上WMS数据库////////////////////////////////////
		if(ModelOneErp2Wms.isNotExist()) {
			try {
        		Logger.info("生成从WMS 到 ERP对账的数据库");
        		ModelOneErp2Wms.createTable();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Logger.error(e);
			}
		}
		if(ModelOneWms2Erp.isNotExist()) {
			try {
        		Logger.info("生成从ERP 到 WMS对账的数据库");
        		ModelOneWms2Erp.createTable();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Logger.error(e);
			}
		}
		if(ModelB2CErpWms.isNotExist()) {
			try {
        		Logger.info("生成从ERP 到 WMS对账的数据库");
        		ModelB2CErpWms.createTable();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Logger.error(e);
			}
		}
		Calendar calendar = Calendar.getInstance();  
        calendar.set(Calendar.HOUR_OF_DAY,23); // 控制时  
        calendar.set(Calendar.MINUTE, 0);       // 控制分  
        calendar.set(Calendar.SECOND, 0);       // 控制秒  
  
        Date time = calendar.getTime();         // 得出执行任务的时间,此处为今天的1：00：00  
  
        Timer timer = new Timer();  
        timer.scheduleAtFixedRate(new TimerTask() {  
            public void run() {  
            	try {
            		Logger.info("执行从WMS导出数据到ERP");
            		ModelOneWms.importWmsTable();
            		ModelOneWmsTzd.importWmsTableTZD();

            		ModelOneErp2Wms.importTable();
            		ModelOneWms2Erp.importTable();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Logger.error(e);
				}
            }  
        }, time, 1000 * 60 * 60 * 24);// 这里设定将延时每天固定执行  
        timer.scheduleAtFixedRate(new TimerTask() {  
            public void run() {  
            	try {
            		Logger.info("每周执行B2C任务，从WMS导出数据到ERP");
            		ModelB2CWMS.importWmsTable();
            		ModelB2CErpWms.importTable();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Logger.error(e);
				}
            }  
        }, time, 1000 * 60 * 60 * 24 * 7);// 这里设定将延时每天固定执行  
	}
	/*public void serve_seach_all()
	{
		List<Map<String, Object>> listSpjhd = new ArrayList<Map<String,Object>>(); 
		new Thread() {
			@Override
	        public void run() {
				int ret = 0;
				try {
					sleep(200);
				} catch (InterruptedException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
				while(true) {
					try {
						List<Map<String, Object>> listNotUpSpjhd = null; 
						listNotUpSpjhd = ModelSpjhd.getNotUpedList();
						for(Map<String,Object> map : listNotUpSpjhd) {
							try {
								DJBH = (String) map.get("DJBH");
								listSpjhd.add(map);
								List<Map<String, Object>> listSpjhdmx = OneJdbc.getSpjhdmx(DJBH);
		        				if(listSpjhd != null && listSpjhd.size() > 0) {
		            				listSpjhd.get(0).put("items", listSpjhdmx);
		        				}
		        				ret = LocTaskSpjhd.postHttpForSpjhdInsert(listSpjhd,listSpjhdmx);
								if(ret == 0 || ret == 200) {
									ModelSpjhd.updateFlag(DJBH);
								}
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								Logger.error(e);
							}
							try {
								sleep(200);
							} catch (InterruptedException e2) {
								// TODO Auto-generated catch block
								Logger.error(e2);
							}
						}
						
					} catch (SQLException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					try {
						List<Map<String, Object>> listNotUpSpthd = null; 
						listNotUpSpthd = ModelSpthd.getNotUpedList();
						for(Map<String,Object> map : listNotUpSpthd) {
							try {
								String spthdDJBH = (String) map.get("DJBH");
								List<Map<String, Object>> listSpthd = new ArrayList<Map<String,Object>>();
								listSpthd.add(map);
								List<Map<String, Object>> listSpjhdmx = OneJdbc.getSpjhdmx(spthdDJBH);
		        				if(listSpthd != null && listSpthd.size() > 0) {
		        					listSpthd.get(0).put("items", listSpjhdmx);
		        				}
		        				ret = LocTaskSpjhd.postHttpForSpjhdInsert(listSpthd,listSpjhdmx);
								if(ret == 0 || ret == 200) {
									ModelSpjhd.updateFlag(spthdDJBH);
								}
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								Logger.error(e);
							}
							try {
								sleep(200);
							} catch (InterruptedException e2) {
								// TODO Auto-generated catch block
								e2.printStackTrace();
							}
						}
						
					} catch (SQLException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
    				try {
						TimeUnit.DAYS.sleep(1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();
	}*/
	public void process_check_spd()
	{
		try {
            try {
				listMtab = OneJdbc.getMtab();
			} catch (SQLException e1) {
				return;
			}
            if(listMtab != null)
			for(Map<String, Object> mdat:listMtab) {
				DJBH = (String) mdat.get("KEY_VALUE");
				actType = (String) mdat.get("ACT_TYPE");
				tabName = (String) mdat.get("TAB_NAME");
				stamp = (String) mdat.get("tmstamp");
				if(DJBH == null || DJBH == "") {
					Logger.error("DJBH is "+DJBH+".关键字值错误，");
					continue;
				}
				if(actType != null) {
    				if(actType.equalsIgnoreCase("delete")) {
    					try {
							OneJdbc.deleteMtab(stamp);
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							Logger.error(e);
						}
    					continue;
    				}
    				if(actType.equalsIgnoreCase("update")) {
    					try {
							OneJdbc.deleteMtab(stamp);
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							Logger.error(e);
						}
    					continue;
    				}
				}
				if(tabName != null) {
    				if(tabName.equalsIgnoreCase("SPJHD")) {
        				try {
        					LocTaskSpjhd.process(DJBH, stamp);
        				} catch (SQLException e) {
							// TODO Auto-generated catch block
							Logger.error(e);
						}
    				}else
    				if(tabName.equalsIgnoreCase("SPTHD")) {
    					try {
							LocTaskSpthd.process(DJBH, stamp);
						} catch (SQLException e) {
        					Logger.error(e);
						}
    				}else {
    					Logger.error("ONE_MTAB没有找到对应的表tabName:"+tabName);
    				}
				}else {
					Logger.error("tabName error!");
				}
			}
			if(delete_error > 10) {
				delete_error = 0;
				delete_err_str = "";
				Logger.error("删除错误累计超过10次，ONE_MTAB删除失败,错误记录："+delete_err_str);
			}
        } catch (InterruptedException e) {
        	Logger.error(e);
        }
	}
	public void serve_check_spd()
	{
		new Thread() {
			@Override
	        public void run() {
				if(ModelMtab.isNotExistTable()) {
					try {
		        		Logger.info("创建ONE_MTAB表,创建SPJHD和SPTHD触发器");
		        		ModelMtab.createTable();
		        		ModelSpjhd.createTrigger();
		        		ModelSpthd.createTrigger();
					} catch (SQLException e) {
					}
				}
				try {
					sleep(1500);
				} catch (InterruptedException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}

            	while(true)
            	{
            		try {
                        try {
							listMtab = OneJdbc.getMtab();
						} catch (SQLException e1) {
							// TODO Auto-generated catch block
							sleep(1000);
							continue;
						}
                        if(listMtab != null)
            			for(Map<String, Object> mdat:listMtab) {
            				DJBH = (String) mdat.get("KEY_VALUE");
            				actType = (String) mdat.get("ACT_TYPE");
            				tabName = (String) mdat.get("TAB_NAME");
            				stamp = (String) mdat.get("tmstamp");
            				if(DJBH == null || DJBH == "") {
            					Logger.error("DJBH is "+DJBH+".关键字值错误，");
            					continue;
            				}
            				if(actType != null) {
	            				if(actType.equalsIgnoreCase("delete")) {
	            					try {
										OneJdbc.deleteMtab(stamp);
									} catch (SQLException e) {
										// TODO Auto-generated catch block
										Logger.error(e);
									}
	            					continue;
	            				}
	            				if(actType.equalsIgnoreCase("update")) {
	            					try {
										OneJdbc.deleteMtab(stamp);
									} catch (SQLException e) {
										// TODO Auto-generated catch block
										Logger.error(e);
									}
	            					continue;
	            				}
            				}
            				if(tabName != null) {
	            				if(tabName.equalsIgnoreCase("SPJHD")) {
		            				try {
		            					LocTaskSpjhd.process(DJBH, stamp);
		            				} catch (SQLException e) {
										// TODO Auto-generated catch block
										Logger.error(e);
									}
	            				}else
	            				if(tabName.equalsIgnoreCase("SPTHD")) {
	            					try {
										LocTaskSpthd.process(DJBH, stamp);
									} catch (SQLException e) {
		            					Logger.error(e);
									}
	            				}else {
	            					Logger.error("ONE_MTAB没有找到对应的表tabName:"+tabName);
	            				}
            				}else {
            					Logger.error("tabName error!");
            				}
	            			sleep(100);
            			}
        				if(delete_error > 10) {
        					delete_error = 0;
        					delete_err_str = "";
        					Logger.error("删除错误累计超过10次，ONE_MTAB删除失败,错误记录："+delete_err_str);
        				}
            			//Thread.currentThread().
            			sleep(100);
        				TimeUnit.SECONDS.sleep(delaySecond);
        				TimeUnit.MINUTES.sleep(delayMinute);
                    } catch (InterruptedException e) {
                        // TODO: handle exception
                    	Logger.error(e);
                    }
            	}
	        }
		}.start();
	}
	/**
	 * ONEMORE 循环定时查询数据库服务
	 * 
	 * */
	public void serve()
	{
		Properties delayProperites = OneConfig.getProperties();
		String tmp = delayProperites.getProperty("second");
		if(tmp != null) {
			delaySecond = Integer.valueOf(tmp);
		}else {
			delaySecond = 10;
		}
		tmp = delayProperites.getProperty("minute");
		if(tmp != null) {
			delayMinute = Integer.valueOf(tmp);
		}
		tmp = delayProperites.getProperty("log_retain_day");
		if(tmp != null) {
			retainDay = Integer.valueOf(tmp);
		}else {
			retainDay = 30;
		}
		//自动清理线程
		//serve_seach_all();
		if(OneConfig.getProperties().containsKey("server_clean") 
				&& OneConfig.getProperties().getProperty("server_clean").equalsIgnoreCase("true"))
		serve_auto_clear();
		//对账单WMS到ERP，和ERP到WMS
		if(OneConfig.getProperties().containsKey("server_wms") 
				&& OneConfig.getProperties().getProperty("server_wms").equalsIgnoreCase("true"))
		serve_auto_import();
		//SCM
		if(OneConfig.getProperties().containsKey("server_spd")
				&& OneConfig.getProperties().getProperty("server_spd").equalsIgnoreCase("true"))
		serve_check_spd();
	}
}
